﻿using System;
using ufida.u9.ait.openapi.utils;
using UFIDA.U9.Base;
using UFIDA.U9.Base.Currency;
using UFIDA.U9.Base.Doc;
using UFIDA.U9.Base.Memo;
using UFIDA.U9.CBO.Enums;
using UFIDA.U9.CBO.FI.MatchLayerSet;
using UFIDA.U9.CBO.FI.Tax;
using UFIDA.U9.CBO.HR.Department;
using UFIDA.U9.CBO.HR.Operator;
using UFIDA.U9.CBO.MFG.Enums;
using UFIDA.U9.CBO.SCM.Enums;
using UFIDA.U9.CBO.SCM.Item;
using UFIDA.U9.CBO.SCM.PickList;
using UFIDA.U9.CBO.SCM.ProjectTask;
using UFIDA.U9.CBO.SCM.Supplier;
using UFIDA.U9.PM.DTOs;
using UFIDA.U9.PM.Enums;
using UFIDA.U9.PM.PO;
using UFIDA.U9.PM.Pub;
using UFIDA.U9.PR.PurchaseRequest;
using UFIDA.U9.SM.DealerSO;
using UFSoft.UBF.Business;

namespace ufida.u9.ait.openapi
{
    internal class SubPOBase
    {
        public static PurchaseOrder ApproveDoc(PurchaseOrder doc)
        {
            U9Utils.ClearCache();
            doc = doc.Key.GetEntity();

            POShipLine shipLine = doc.POLines[0].POShiplines[0];
            //提交
            SinglePoShipLineBP bp1 = new SinglePoShipLineBP();
            bp1.ActionType = ActivateTypeEnum.ApprovingAct;
            bp1.PoShipLineKey = shipLine.Key;
            bp1.PoShipLineSysVersion = shipLine.SysVersion;
            bp1.PoLineSysVersion = shipLine.POLine.SysVersion;
            bp1.PoSysVersion = doc.SysVersion;
            POSysVersionDTO retdto1 = bp1.Do();

            //审核
            SinglePoShipLineBP bp = new SinglePoShipLineBP();
            bp.ActionType = ActivateTypeEnum.ApprovedAct;
            bp.PoShipLineKey = shipLine.Key;
            bp.PoShipLineSysVersion = shipLine.SysVersion;
            bp.PoLineSysVersion = shipLine.POLine.SysVersion;
            bp.PoSysVersion = doc.SysVersion;
            POSysVersionDTO retdto = bp.Do();

            return doc;
        }

        public static PurchaseOrder CreateDoc(POAITDTOData dto)
        {
            PurchaseOrder doc = null;

            using (ISession session = Session.Open())
            {
                doc = CreateHead(dto);
                doc = CreateLines(doc, dto);
                doc = UpdateHead(doc);
                session.Commit();
            }
            return doc;
        }

        private static PurchaseOrder UpdateHead(PurchaseOrder doc)
        {
            //更新表头汇总金额
            decimal totalMnyAC = 0;
            decimal totalMnyTC = 0;
            decimal totalMnyFC = 0;
            decimal totalTaxAC = 0;
            decimal totalTaxTC = 0;
            decimal totalTaxFC = 0;
            decimal totalNetMnyAC = 0;
            decimal totalNetMnyTC = 0;
            decimal totalNetMnyFC = 0;

            foreach (var line in doc.POLines)
            {
                totalMnyAC += line.TotalMnyAC;
                totalMnyTC += line.TotalMnyTC;
                totalMnyFC += line.TotalMnyFC;
                totalTaxAC += line.TotalTaxAC;
                totalTaxTC += line.TotalTaxTC;
                totalTaxFC += line.TotalTaxFC;
                totalNetMnyAC += line.NetMnyAC;
                totalNetMnyTC += line.NetMnyTC;
                totalNetMnyFC += line.NetMnyFC;

            }

            doc.TotalMnyAC = totalMnyAC;
            doc.TotalMnyTC = totalMnyTC;
            doc.TotalMnyFC = totalMnyFC;
            doc.TotalTaxMnyAC = totalTaxAC;
            doc.TotalTaxMnyTC = totalTaxTC;
            doc.TotalTaxMnyFC = totalTaxFC;
            doc.TotalNetMnyAC = totalNetMnyAC;
            doc.TotalNetMnyTC = totalNetMnyTC;
            doc.TotalNetMnyFC = totalNetMnyFC;

            return doc;
        }
        /// <summary>
        /// 创建采购订单行
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="linedto"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static POLine CreateLine(PurchaseOrder doc, POLineAITDTOData linedto)
        {
            POLine line = POLine.Create(doc);
            line.DocLineNo = linedto.DocLineNo;
            line.CurrentOrg = doc.Org;
            line.BOMOwner = doc.Org;

            //料品/单位
            if (linedto.ItemInfo == null) throw new Exception("ItemInfo 为空");
            ItemMaster item = EntityUtils.GetEntityByCode<ItemMaster>(linedto.ItemInfo.ItemCode);

            line.ItemInfo = new ItemInfo()
            {
                ItemID = item,
                ItemCode = item.Code,
                ItemName = item.Name,
            };
            line.WeightUOM = item.WeightUom;
            line.VolumeUOM = item.BulkUom;
            line.TradeUOM = item.PurchaseUOM;
            line.TradeBaseUOM = item.PurchaseUOM.BaseUOM;
            line.ReqUOM = item.PurchaseUOM;
            line.ReqBaseUOM = item.PurchaseUOM.BaseUOM;
            line.StoreUOM = item.InventoryUOM;
            line.PriceUOM = item.PriceUOM;
            line.PriceBaseUOM = item.PriceUOM.BaseUOM;
            line.CostUOM = item.CostUOM;
            line.CostBaseUOM = item.CostUOM.BaseUOM;

            //数量
            line.PurQtyTU = linedto.PurQtyTU;
            line.PurQtyPU = linedto.PurQtyTU;
            line.PurQtyCU = linedto.PurQtyTU;
            line.SupplierConfirmQtyTU = linedto.PurQtyTU;
            line.SupplierConfirmQtyPU = linedto.PurQtyTU;
            line.SupplierConfirmQtyCU = linedto.PurQtyTU;
            line.ReqQtyTU = linedto.PurQtyTU;
            line.ReqQtyPU = linedto.PurQtyTU;
            line.ReqQtyCU = linedto.PurQtyTU;

            //单价/金额/税额
            if (linedto.TaxSchedule != null)
            {
                //优先传入
                line.TaxSchedule = EntityUtils.GetEntityByCode<TaxSchedule>(linedto.TaxSchedule.Code);
            }
            else if (item.PurchaseInfo.PurchaseTaxSchedule != null)
            {
                //其次料品
                line.TaxSchedule = item.PurchaseInfo.PurchaseTaxSchedule;
            }
            else
            {
                //其次单头
                line.TaxSchedule = doc.TaxSchedule;
            }
            if (line.TaxSchedule == null) throw new Exception("行TaxSchedule为空");
            line.TaxRate = EntityUtils.GetTaxRate(line.TaxSchedule);

            //最终价 含税价
            line.FinallyPriceTC = linedto.FinallyPriceTC;
            line.FinallyPriceFC = linedto.FinallyPriceTC;
            line.FinallyPriceAC = linedto.FinallyPriceTC;
            line.ApprovedPriceTC = linedto.FinallyPriceTC;
            line.ApprovedPriceAC = linedto.FinallyPriceTC;
            line.OrderPriceTC = linedto.FinallyPriceTC;
            line.SystemPriceTC = linedto.FinallyPriceTC;
            //不含税价=含税价/(1+税率)
            line.NetFinallyPriceTC = linedto.FinallyPriceTC / (1 + line.TaxRate);
            line.NetFinallyPriceTC = EntityUtils.GetRoundMny(doc.TC, line.NetFinallyPriceTC);//精度
            line.NetFinallyPriceFC = line.NetFinallyPriceTC;
            line.NetFinallyPriceAC = line.NetFinallyPriceTC;
            line.PriceDifferenceTC = line.NetFinallyPriceTC;
            line.PriceDifferenceFC = line.NetFinallyPriceTC;
            line.PriceDifferenceAC = line.NetFinallyPriceTC;
            //价税合计
            line.TotalMnyTC = linedto.TotalMnyTC;
            line.TotalMnyFC = linedto.TotalMnyTC;
            line.TotalMnyAC = linedto.TotalMnyTC;

            //未税金额=价税合计/(1+税率)
            line.NetMnyTC = line.TotalMnyTC / (1 + line.TaxRate);
            line.NetMnyTC = EntityUtils.GetRoundMny(doc.TC, line.NetMnyTC);//精度
            line.NetMnyFC = line.NetMnyTC;
            line.NetMnyAC = line.NetMnyTC;
            line.PriceDifferenceMnyTC = line.NetMnyTC;
            line.PriceDifferenceMnyFC = line.NetMnyTC;
            line.PriceDifferenceMnyAC = line.NetMnyTC;

            //税额=价税合计-未税金额
            line.TotalTaxTC = line.TotalMnyTC - line.NetMnyTC;
            line.TotalTaxFC = line.TotalTaxTC;
            line.TotalTaxAC = line.TotalTaxTC;

            //扩展字段处理
            if (linedto.DescFlexSegments != null)
            {
                line.DescFlexSegments = new UFIDA.U9.Base.FlexField.DescFlexField.DescFlexSegments();
                DTOUtils.DTOPropCopy(linedto.DescFlexSegments, line.DescFlexSegments);
            }

            //单行备注
            if (linedto.Memo != null)
            {
                if (line.POMemoes != null && line.POMemoes.Count > 0)
                {
                    line.POMemoes[0].Description = linedto.Memo;
                }
                else
                {
                    POMemo memo = POMemo.Create(line);
                    memo.LineNO = 10;
                    memo.Description = linedto.Memo;
                    memo.DocMemoType = DocMemoTypeEnum.LineHead;
                    memo.CurrentOrg = doc.Org;
                }
            }

            //其它
            line.BOMEffectiveDate = doc.BusinessDate;
            line.PriceSource = PriceSourceEnum.Custom;//价格来源=手工
            line.QuantityType = UsageQuantityTypeEnum.Variable;//数量类型=变动
            line.Project = EntityUtils.GetEntityByCode<Project>(linedto.Project);
            line.RcvBy = doc.ReceiptRule;
            line.PaymentTerm = doc.Supplier.Supplier.PaymentTerm;
            line.ConfirmTerm = doc.ConfirmTerm;
            line.Payer = doc.Supplier;
            line.PayerSite = doc.ShiptoSite;
            line.BilltoSite = doc.ShiptoSite;
            line.TUToTBURateB = 1;
            line.TUToTBURate = 1;
            line.TBUToPBURate = 1;
            line.TBUToCBURate = 1;
            line.PUToPBURate = 1;
            line.CUToCBURate = 1;
            line.RUToRBURate = 1;
            line.TradePathEditalbe = true;
            line.OriginalPriceIncludeTax = true;
            line.IsTUCanChange = true;
            line.IsSUCanChange = true;
            line.IsPUCanChange = true;
            line.IsPriceModify = true;
            line.IsMRPDemand = true;
            line.IsKITRcvCanChange = true;
            line.IsForceWholeSet = linedto.IsForceWholeSet;//强制齐套
            line.IsApprovedPrice = true;
            line.CanChangeItemVersion = true;

            line.IsPresent = linedto.IsPresent;

            //来源单据处理
            if (linedto.SrcDocInfo != null)
            {
                //存在来源单据 0-手工 1-PR
                //无来源时,SrcDocType=0
                if (linedto.SrcDocType == 1)
                {
                    //来源=请购单
                    PRLine prLine = PRLine.Finder.Find($"PR.DocNo='{linedto.SrcDocInfo.SrcDocNo}' and DocLineNo={linedto.SrcDocInfo.SrcDocLineNo}", null);
                    if (prLine == null)
                        throw new Exception($"查询请购单行失败,单号[{linedto.SrcDocInfo.SrcDocNo}]行号[{linedto.SrcDocInfo.SrcDocLineNo}]");
                    if (prLine.ItemInfo.ItemCode != item.Code)
                        throw new Exception($"传入物料[{item.Code}]与来源物料[{prLine.ItemInfo.ItemCode}]不同");

                    line.SrcDocType = POSrcDocTypeEnum.PR;
                    line.PRNO = prLine.PR.DocNo;
                    line.PRID = prLine.PR.ID;
                    line.PRLineID = prLine.ID;
                    line.SrcDocInfo = new UFIDA.U9.CBO.SCM.PropertyTypes.SrcDocInfo()
                    {
                        SrcDocTransTypeName = prLine.PR.DocType.Name,
                        SrcDocTransType = new UFIDA.U9.Base.PropertyTypes.BizEntityKey()
                        {
                            EntityID = prLine.PR.DocType.ID,
                            EntityType = prLine.PR.DocType.Key.EntityType,
                        },
                        SrcDocOrg = prLine.PR.Org,
                        SrcDocNo = prLine.PR.DocNo,
                        SrcDocLineNo = prLine.DocLineNo,
                        SrcDocLine = new UFIDA.U9.Base.PropertyTypes.BizEntityKey()
                        {
                            EntityID = prLine.ID,
                            EntityType = prLine.Key.EntityType,
                        },
                        SrcDocDate = prLine.PR.BusinessDate,
                        SrcDoc = new UFIDA.U9.Base.PropertyTypes.BizEntityKey()
                        {
                            EntityID = prLine.PR.ID,
                            EntityType = prLine.PR.Key.EntityType,
                        }
                    };
                }
                else
                {
                    throw new Exception($"SrcDocType[{linedto.SrcDocType}]不支持该类型!");
                }
            }

            //创建计划行
            CreateShipLine(doc, line);
            //创建 税子表
            CreatePOTaxs(doc, line);
            //创建供应链备料
            CreateSCMPick(doc, line, linedto);

            return line;
        }
        /// <summary>
        /// 创建采购订单行集合
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="dto"></param>
        /// <returns></returns>
        private static PurchaseOrder CreateLines(PurchaseOrder doc, POAITDTOData dto)
        {
            int DocLineNo = 0;
            foreach (var linedto in dto.POLines)
            {
                DocLineNo += 10;
                if (linedto.DocLineNo <= 0)
                    linedto.DocLineNo = DocLineNo;
                CreateLine(doc, linedto);
            }

            return doc;
        }
        /// <summary>
        /// 创建委外订单备料行
        /// </summary>
        /// <param name="head">备料单头</param>
        /// <param name="picklinedto">备料行dto</param>
        /// <returns>备料行</returns>
        public static SCMPickList CreateSCMPickLine(PicKHead head, SCMPickListAITDTOData picklinedto)
        {
            POLine line = head.POLine;
            PurchaseOrder doc = head.POLine.PurchaseOrder;

            SCMPickList pickline = SCMPickList.Create(head);
            if (picklinedto.PickLineNo <= 0)
                throw new Exception("PickLineNo为空!");
            pickline.PickLineNo = picklinedto.PickLineNo;
            //料品/单位
            if (picklinedto.ItemInfo == null) throw new Exception("ItemInfo 为空");
            ItemMaster item = EntityUtils.GetEntityByCode<ItemMaster>(picklinedto.ItemInfo.ItemCode);
            pickline.ItemInfo = new ItemInfo()
            {
                ItemID = item,
                ItemCode = item.Code,
                ItemName = item.Name,
            };
            pickline.RcvUOM = item.PurchaseUOM;
            pickline.RcvBaseUOM = item.PurchaseUOM.BaseUOM;
            pickline.IssueUOM = item.MaterialOutUOM;
            pickline.IssueBaseUOM = item.MaterialOutUOM.BaseUOM;
            pickline.CoUOM = item.CostUOM;
            pickline.CostBaseUOM = item.CostUOM.BaseUOM;
            //数量
            pickline.ActualReqQty = picklinedto.ActualReqQty;
            pickline.StdReqQty = picklinedto.ActualReqQty;
            pickline.QPA = pickline.ActualReqQty / line.PurQtyTU; //每装配件数量
            //扩展字段处理
            if (picklinedto.DescFlexField != null)
            {
                pickline.DescFlexField = new UFIDA.U9.Base.FlexField.DescFlexField.DescFlexSegments();
                DTOUtils.DTOPropCopy(picklinedto.DescFlexField, pickline.DescFlexField);
            }
            //其它属性
            pickline.ConsignProcessItemSrc = ConsignProcessItemSrcEnum.IssuedByConsignee;//	委托料品来源=受托方领料
            pickline.SUToSBURate = 1;
            pickline.IUToIBURate = 1;
            pickline.IBUToSBURate = 1;
            pickline.IBUToCBURate = 1;
            pickline.CUToCBURate = 1;
            pickline.SupplyOrg = doc.Org;
            pickline.QtyType = UsageQuantityTypeEnum.Variable;
            pickline.PlanReqDate = DateTime.Now;
            pickline.ActualReqDate = DateTime.Now;
            pickline.IsWholeSetIssue= picklinedto.IsWholeSetIssue;//齐套发料
            pickline.RcvApproveSetCheck= picklinedto.RcvApproveSetCheck;//收货审核齐套
            pickline.RcvSaveSetCheck= picklinedto.RcvSaveSetCheck;//收货保存齐套

            return pickline;
        }
        /// <summary>
        /// 创建委外订单备料表头
        /// </summary>
        /// <param name="doc">委外订单头</param>
        /// <param name="line">委外订单行</param>
        public static PicKHead CreatePicKHead(PurchaseOrder doc, POLine line)
        {
            //创建表头
            PicKHead pick = PicKHead.Create();
            pick.Org = doc.Org;
            pick.SrcDoc = new UFIDA.U9.CBO.SCM.PropertyTypes.SrcDocInfo()
            {
                SrcDocVer = doc.Version,
                SrcDocOrg = doc.Org,
                SrcDocNo = doc.DocNo,
                SrcDocLineNo = line.DocLineNo,
                SrcDocLine = new UFIDA.U9.Base.PropertyTypes.BizEntityKey()
                {
                    EntityID = line.Key.ID,
                    EntityType = line.Key.EntityType,
                },
                SrcDocDate = doc.BusinessDate,
                SrcDoc = new UFIDA.U9.Base.PropertyTypes.BizEntityKey()
                {
                    EntityID = doc.Key.ID,
                    EntityType = doc.Key.EntityType,
                },
            };
            pick.Project = line.Project;
            pick.POLine = line;

            //更新POLine
            line.SCMPickHead = pick;

            return pick;
        }

        /// <summary>
        /// 创建委外订单备料
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="line"></param>
        /// <param name="linedto"></param>
        /// <exception cref="Exception"></exception>
        private static void CreateSCMPick(PurchaseOrder doc, POLine line, POLineAITDTOData linedto)
        {
            if (linedto.SCMPickList == null || linedto.SCMPickList.Count == 0) return;

            //创建表头
            PicKHead pick = CreatePicKHead(doc, line);

            //创建表体
            short rowno = 0;
            foreach (var picklinedto in linedto.SCMPickList)
            {
                rowno += 10;
                if (picklinedto.PickLineNo <= 0)
                {
                    picklinedto.PickLineNo = rowno;
                }
                CreateSCMPickLine(pick, picklinedto);
            }
        }

        private static void CreatePOTaxs(PurchaseOrder doc, POLine line)
        {
            POTax taxline = POTax.Create(line);
            taxline.TaxType = line.TaxSchedule.TaxScheduleTaxs[0].Tax;
            taxline.TaxRate = line.TaxRate;
            taxline.TaxMnyTC = line.TotalTaxTC;
            taxline.TaxMnyFC = line.TotalTaxFC;
            taxline.TaxMnyAC = line.TotalTaxAC;
        }

        private static void CreateShipLine(PurchaseOrder doc, POLine line)
        {
            POShipLine shipLine = POShipLine.Create(line);
            shipLine.Wh = line.ItemInfo.ItemID.InventoryInfo.Warehouse;
            shipLine.SubLineNo = 10;
            shipLine.ShiptoSite = doc.ShiptoSite;
            shipLine.RequireMan = doc.PurOper;
            shipLine.RequireDept = doc.PurDept;
            //组织
            shipLine.CurrentOrg = doc.Org;
            shipLine.AccountOrg = doc.Org;
            shipLine.ShipperOrg = doc.Org;
            shipLine.SettleOrg = doc.Org;
            shipLine.RequireOrg = doc.Org;
            shipLine.RcvOrg = doc.Org;
            //料品/单位
            shipLine.ItemInfo = line.ItemInfo;
            shipLine.WeightUOM = line.WeightUOM;
            shipLine.VolumeUOM = line.VolumeUOM;
            shipLine.TradeUOM = line.TradeUOM;
            shipLine.TradeBaseUOM = line.TradeBaseUOM;
            shipLine.CostUOM = line.CostUOM;
            shipLine.CostBaseUOM = line.CostBaseUOM;
            shipLine.StoreUOM = line.StoreUOM;
            shipLine.PriceUOM = line.PriceUOM;
            shipLine.PriceBaseUOM = line.PriceBaseUOM;
            //来源信息
            if (line.SrcDocInfo != null)
            {
                if (line.SrcDocType == POSrcDocTypeEnum.PR)
                {
                    //来源请购单
                    PRLine prLine = PRLine.Finder.FindByID(line.SrcDocInfo.SrcDocLine.EntityID);
                    if (prLine == null)
                        throw new Exception("查询请购单行失败!");
                    shipLine.SrcDocVersion = -2;
                    shipLine.SrcDocType = POSrcDocTypeEnum.PR;
                    shipLine.SrcDocPRLine = prLine.ID;
                    shipLine.SrcDocPRDocNo = prLine.PR.DocNo;
                    shipLine.SrcDocPR = prLine.PR.ID;
                    shipLine.SrcDocInfo = line.SrcDocInfo;
                    shipLine.SrcBudgetOrg = prLine.PR.Org.ID;
                    shipLine.SrcBudgetLine = prLine.ID;
                    shipLine.SrcBudgetDocType = prLine.Key.EntityType;
                    shipLine.ReqUOM = line.ReqUOM;
                    shipLine.ReqBaseUOM = line.ReqBaseUOM;
                }

            }
            //数量
            shipLine.ReqQtyTU = line.ReqQtyTU;
            shipLine.ReqQtyPU = line.ReqQtyPU;
            shipLine.ReqQtyCU = line.ReqQtyCU;
            shipLine.SupplierConfirmQtyTU = line.SupplierConfirmQtyTU;
            shipLine.SupplierConfirmQtyPU = line.SupplierConfirmQtyTU;
            shipLine.SupplierConfirmQtyCU = line.SupplierConfirmQtyTU;
            shipLine.PlanArriveQtyTU = line.PurQtyTU;
            shipLine.PlanArriveQtyPU = line.PurQtyTU;
            shipLine.PlanArriveQtyCU = line.PurQtyTU;
            shipLine.DeficiencyQtyTU = line.PurQtyTU;
            shipLine.DeficiencyQtyPU = line.PurQtyPU;
            shipLine.DeficiencyQtyCU = line.PurQtyCU;
            //单价/金额/税额
            shipLine.TotalTaxTC = line.TotalTaxTC;
            shipLine.TotalMnyTC = line.TotalMnyTC;
            shipLine.TotalMnyFC = line.TotalMnyFC;
            shipLine.TotalMnyAC = line.TotalMnyAC;
            shipLine.NetMnyTC = line.NetMnyTC;
            shipLine.NetMnyFC = line.NetMnyFC;
            shipLine.NetMnyAC = line.NetMnyAC;
            //日期
            shipLine.VPConfirmTradeDate = doc.BusinessDate;
            shipLine.PlanArriveDate = doc.BusinessDate;
            shipLine.NeedPODate = doc.BusinessDate;
            shipLine.DeliveryDate = doc.BusinessDate;
            //其它
            shipLine.Project = line.Project;
            shipLine.TUToTBURateB = 1;
            shipLine.TUToTBURate = 1;
            shipLine.TBUToPBURate = 1;
            shipLine.TBUToCBURate = 1;
            shipLine.PUToPBURate = 1;
            shipLine.CUToCBURate = 1;
            shipLine.RUToRBURate = 1;
            shipLine.IsTUCanChange = true;
            shipLine.IsSUCanChange = true;
            shipLine.IsSeiBanEditable = true;
            shipLine.IsPUCanChange = true;
            shipLine.IsCUCanChange = true;

        }

        private static PurchaseOrder CreateHead(POAITDTOData dto)
        {
            PurchaseOrder doc = PurchaseOrder.Create();
            //doc.DocNo = dto.DocNo;
            if (dto.BusinessDate != null)
            {
                doc.BusinessDate = DateTime.Parse(dto.BusinessDate);
            }
            else
            {
                doc.BusinessDate = DateTime.Now;
            }

            //组织
            doc.Org = Context.LoginOrg;
            doc.SettleOrg = Context.LoginOrg;
            doc.AccountOrg = Context.LoginOrg;

            //记账期间
            doc.PostPeriod = EntityUtils.getPostPeriod(doc.BusinessDate);

            //单据类型
            if (dto.DocumentType == null) throw new Exception($"DocumentType 为空");
            doc.DocumentType = EntityUtils.GetEntityByCode<PODocType>(dto.DocumentType.Code);

            //币种
            if (dto.TC != null)
            {
                doc.TC = EntityUtils.GetEntityByCode<Currency>(dto.TC);
            }
            else
            {
                doc.TC = EntityUtils.GetEntityByCode<Currency>("C001");
            }
            doc.FC = doc.TC;
            doc.AC = doc.TC;
            //供应商/位置
            if (dto.Supplier == null) throw new Exception($"Supplier 为空");
            Supplier supplier = EntityUtils.GetEntityByCode<Supplier>(dto.Supplier);
            doc.Supplier = new SupplierMISCInfo()
            {
                Code = supplier.Code,
                Supplier = supplier,
                Name = supplier.Name,
                ShortName = supplier.ShortName,
            };
            doc.ShiptoSite = new SupplierSiteMISCInfo()
            {
                SupplierSite = supplier.SupplierSites[0],
                Code = supplier.Code,
                Name = supplier.Name,
            };
            //收货规则/立账条件
            doc.ReceiptRule = supplier.ReceiptRule;
            doc.ConfirmTerm = supplier.APConfirmTerm;
            //doc.ConfirmAccording = EntityUtils.GetEntityByCode<AccrueBy>("SD09");

            //税组合
            if (dto.TaxSchedule != null)
            {
                doc.TaxSchedule = EntityUtils.GetEntityByCode<TaxSchedule>(dto.TaxSchedule.Code);
            }
            else if (supplier.TaxSchedule != null)
            {
                doc.TaxSchedule = supplier.TaxSchedule;
            }
            if (doc.TaxSchedule != null)
            {
                doc.TaxRate = EntityUtils.GetTaxRate(doc.TaxSchedule);
            }


            //扩展字段处理
            if (dto.DescFlexField != null)
            {
                doc.DescFlexField = new UFIDA.U9.Base.FlexField.DescFlexField.DescFlexSegments();
                DTOUtils.DTOPropCopy(dto.DescFlexField, doc.DescFlexField);
            }
            //单头备注
            if (dto.Memo != null)
            {
                if (doc.POMemos != null && doc.POMemos.Count > 0)
                {
                    doc.POMemos[0].Description = dto.Memo;
                }
                else
                {
                    POMemo memo = POMemo.Create(doc);
                    memo.LineNO = 10;
                    memo.Description = dto.Memo;
                    memo.DocMemoType = DocMemoTypeEnum.DocHead;
                    memo.CurrentOrg = doc.Org;
                }
            }
            //其它
            doc.BizType = BusinessTypeEnum.PM055;//全程委外采购
            doc.PurOper = EntityUtils.GetEntityByCode<Operators>(dto.PurOper);
            doc.PurDept = EntityUtils.GetEntityByCode<Department>(dto.PurDept);
            doc.POPriority = 99;
            doc.MatchLayer = MatchGradeEnum.Way4;
            doc.Version = 1;
            doc.WindageRatio = 0.05M;
            doc.RiskRate = 1.1M;

            doc.TCToACExchRate = 1;
            doc.ACToFCExchRate = 1;
            doc.IsTCToACCanChange = true;
            doc.IsTCCanChange = true;
            doc.IsReceiptRuleChange = true;
            doc.IsPriceIncludeTax = true;
            doc.IsPLChange = true;
            doc.IsExchRateCanChange = true;
            doc.IsConfirmChange = true;
            doc.IsACCanChange = true;
            return doc;
        }
    }
}
